/**
 * SEO优化 Composable
 * 用于生成结构化数据和优化SEO标签
 */

interface ToolSchemaData {
  name: string
  description: string
  url: string
  logo?: string
  rating?: number
  reviewCount?: number
  price?: string
  category?: string
}

interface ArticleSchemaData {
  title: string
  description: string
  url: string
  author: string
  publishDate: string
  modifiedDate?: string
  image?: string
}

export const useSEO = () => {
  const config = useRuntimeConfig()
  const siteUrl = config.public.siteUrl || 'https://devtoolsnav.com'

  /**
   * 生成工具的结构化数据（SoftwareApplication Schema）
   */
  const generateToolSchema = (tool: ToolSchemaData) => {
    const schema: any = {
      '@context': 'https://schema.org',
      '@type': 'SoftwareApplication',
      name: tool.name,
      description: tool.description,
      url: tool.url,
      applicationCategory: tool.category || 'DeveloperApplication',
      operatingSystem: 'Web',
    }

    if (tool.logo) {
      schema.image = tool.logo
    }

    if (tool.rating && tool.reviewCount) {
      schema.aggregateRating = {
        '@type': 'AggregateRating',
        ratingValue: tool.rating,
        ratingCount: tool.reviewCount,
        bestRating: 5,
        worstRating: 1,
      }
    }

    if (tool.price) {
      schema.offers = {
        '@type': 'Offer',
        price: tool.price === '免费' ? '0' : tool.price,
        priceCurrency: 'CNY',
      }
    }

    return schema
  }

  /**
   * 生成文章的结构化数据（Article Schema）
   */
  const generateArticleSchema = (article: ArticleSchemaData) => {
    return {
      '@context': 'https://schema.org',
      '@type': 'Article',
      headline: article.title,
      description: article.description,
      url: article.url,
      author: {
        '@type': 'Person',
        name: article.author,
      },
      publisher: {
        '@type': 'Organization',
        name: 'DevToolsHub',
        logo: {
          '@type': 'ImageObject',
          url: `${siteUrl}/logo.png`,
        },
      },
      datePublished: article.publishDate,
      dateModified: article.modifiedDate || article.publishDate,
      image: article.image || `${siteUrl}/og-image.png`,
    }
  }

  /**
   * 生成网站的结构化数据（WebSite Schema）
   */
  const generateWebsiteSchema = () => {
    return {
      '@context': 'https://schema.org',
      '@type': 'WebSite',
      name: 'DevToolsNav',
      alternateName: '开发者工具导航',
      url: siteUrl,
      description: '精选开发者工具导航平台，发现最好用的开发工具，提升开发效率',
      potentialAction: {
        '@type': 'SearchAction',
        target: {
          '@type': 'EntryPoint',
          urlTemplate: `${siteUrl}/tools?search={search_term_string}`,
        },
        'query-input': 'required name=search_term_string',
      },
    }
  }

  /**
   * 生成面包屑导航结构化数据
   */
  const generateBreadcrumbSchema = (items: { name: string; url: string }[]) => {
    return {
      '@context': 'https://schema.org',
      '@type': 'BreadcrumbList',
      itemListElement: items.map((item, index) => ({
        '@type': 'ListItem',
        position: index + 1,
        name: item.name,
        item: item.url,
      })),
    }
  }

  /**
   * 生成组织结构化数据
   */
  const generateOrganizationSchema = () => {
    return {
      '@context': 'https://schema.org',
      '@type': 'Organization',
      name: 'DevToolsNav',
      alternateName: '开发者工具导航',
      url: siteUrl,
      logo: `${siteUrl}/logo.png`,
      description: '精选开发者工具导航平台',
      sameAs: [
        // 社交媒体链接（如果有的话）
        // 'https://twitter.com/devtoolshub',
        // 'https://github.com/devtoolshub',
      ],
    }
  }

  /**
   * 设置SEO标签
   */
  const setSEO = (options: {
    title: string
    description: string
    keywords?: string[]
    image?: string
    url?: string
    type?: string
    schema?: any
  }) => {
    const { title, description, keywords, image, url, type, schema } = options

    const seoTitle = title ? `${title} - DevToolsHub` : 'DevToolsHub - 开发者工具导航'
    const seoImage = image || `${siteUrl}/og-image.png`
    const seoUrl = url || siteUrl
    const seoType = type || 'website'

    const head: any = {
      title: seoTitle,
      meta: [
        { name: 'description', content: description },
        // Open Graph
        { property: 'og:title', content: seoTitle },
        { property: 'og:description', content: description },
        { property: 'og:image', content: seoImage },
        { property: 'og:url', content: seoUrl },
        { property: 'og:type', content: seoType },
        // Twitter Card
        { name: 'twitter:title', content: seoTitle },
        { name: 'twitter:description', content: description },
        { name: 'twitter:image', content: seoImage },
      ],
      link: [
        { rel: 'canonical', href: seoUrl },
      ],
    }

    if (keywords && keywords.length > 0) {
      head.meta.push({
        name: 'keywords',
        content: keywords.join(', '),
      })
    }

    // 添加结构化数据
    if (schema) {
      head.script = [
        {
          type: 'application/ld+json',
          innerHTML: JSON.stringify(schema),
        },
      ]
    }

    useHead(head)
  }

  return {
    generateToolSchema,
    generateArticleSchema,
    generateWebsiteSchema,
    generateBreadcrumbSchema,
    generateOrganizationSchema,
    setSEO,
  }
}


